<template>
  <a-modal :open="open" width="640px" :title="rowData.id ? '修改病历文书目录' : '新增病历文书目录'" centered ok-text="保存" @ok="onOk" @cancel="onCancel">
    <a-form :model="formState" class="form-style-flex" :label-col="{ style: { width: '120px' } }">
      <a-form-item label="类型" class="w-full mt-2">
        {{ categroyEnum[store.categroyType] }}
      </a-form-item>
      <a-form-item label="上级目录" class="w-full" v-bind="validateInfos.id">
        <a-tree-select
          v-model:value="formState.id"
          :loading="loading"
          style="width: 100%"
          :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
          allow-clear
          :disabled="!!rowData.id"
          tree-default-expand-all
          :tree-data="treeData"
          tree-node-filter-prop="label"
          placeholder="请选择"
          :field-names="{
            label: 'categoryName',
            key: 'id',
            value: 'id'
          }"
        />
      </a-form-item>
      <a-form-item label="病历文书名称" v-bind="validateInfos.categroyName" class="w-full">
        <a-input v-model:value="formState.categroyName" placeholder="请输入" />
      </a-form-item>
      <a-form-item label="顺序号" v-bind="validateInfos.outOrder" class="w-full">
        <a-input v-model:value="formState.outOrder" placeholder="请输入" />
      </a-form-item>
      <a-form-item label="科室" v-bind="validateInfos.deptId" class="w-full mb-20">
        <SelectSection v-model:value="formState.deptId" multiple />
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script setup>
import { ref } from 'vue'
import { message } from 'ant-design-vue'
import useStore from '../store'
// import { post } from '@/utils/request'
const store = useStore()
const emit = defineEmits(['update:open', 'success'])
const props = defineProps({
  open: Boolean,
  rowData: {
    type: Object,
    default: () => ({})
  }
})
const categroyEnum = ref(['门诊病历', '住院病历', '护理文书', '检查报告', '手术文书'])
const loading = ref(false)
const treeData = ref([])
const requestData = ref({})
const formState = ref({
  id: undefined,
  categroyName: ''
})
const rulesState = ref({
  id: [{ required: true, message: '请选择上级目录' }],
  categroyName: [{ required: true, message: '请输入病历文书名称' }]
})
const { resetFields, validateInfos } = useForm(formState, rulesState)

// 获取文书
const getCategoryTree = async () => {
  loading.value = true
  const { code, data, msg } = await post('/emr/emrCategory/getEmrCategoryByTree', {
    categroyType: store.categroyType
  })
  if (code !== 0) return message.error(msg)
  loading.value = false
  treeData.value = filterNodesByTemplate(data)
}

// 保存
const onOk = async () => {
  if (props.rowData.id) {
    requestData.value = {
      id: props.rowData.id,
      parentId: formState.value.id === '-' ? undefined : formState.value.id,
      categroyName: formState.value.categroyName,
      categroyType: store.categroyType,
      outOrder: formState.value.outOrder,
      deptId: formState.value.deptId
    }
  } else {
    requestData.value = {
      parentId: formState.value.id === '-' ? undefined : formState.value.id,
      categroyName: formState.value.categroyName,
      categroyType: store.categroyType,
      outOrder: formState.value.outOrder,
      deptId: formState.value.deptId
    }
  }
  const { code, msg } = await post('/emr/emrCategory/doSaveEmrCategory', requestData.value)
  if (code !== 0) return message.error(msg)
  message.success('保存成功')
  onCancel()
  emit('success')
}

// 关闭
const onCancel = () => {
  emit('update:open', false)
  resetFields()
}

// 过滤掉 template 字段为 true 的节点及其子节点
const filterNodesByTemplate = (nodes = []) => {
  const filteredNodes = []
  nodes.forEach((node) => {
    if (node.template === true) {
      return
    }
    if (node.children && node.children.length > 0) {
      node.children = filterNodesByTemplate(node.children)
    }
    filteredNodes.push(node)
  })

  return filteredNodes
}
watch(
  () => props.open,
  (val) => {
    if (val) {
      if (props.rowData.categoryName) {
        formState.value = {
          id: props.rowData.parentId || '-',
          categroyName: props.rowData.categoryName,
          outOrder: props.rowData.outOrder,
          deptId: props.rowData.deptId
        }
      } else {
        formState.value = { id: '-' }
      }
      getCategoryTree()
    } else {
      resetFields()
    }
  }
)
</script>
